package com.lhl.jwt.security.configs;

import com.lhl.jwt.handler.JwtAuthenticationFailureHandler;
import com.lhl.jwt.security.filters.MobileCodeAuthenticationFilter;
import com.lhl.jwt.service.JwtUserDetailsService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;


public class MobileConfigurer<T extends MobileConfigurer<T, B>, B extends HttpSecurityBuilder<B>>
		extends AbstractHttpConfigurer<T, B> {

	private MobileCodeAuthenticationFilter filter;

	private JwtUserDetailsService jwtUserDetailsService;

	public MobileConfigurer(JwtUserDetailsService jwtUserDetailsService) {
		filter = new MobileCodeAuthenticationFilter();
		this.jwtUserDetailsService = jwtUserDetailsService;
	}

	@Override
	public void configure(B builder) throws Exception {
		filter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
		filter.setJwtUserDetailsService(jwtUserDetailsService);

		filter = postProcess(filter);
		builder.addFilterBefore(filter, LogoutFilter.class);
	}

	public MobileConfigurer<T, B> authenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
		filter.setAuthenticationSuccessHandler(successHandler);
		return this;
	}

	public MobileConfigurer<T, B> authenticationFailureHandler(JwtAuthenticationFailureHandler jwtAuthenticationFailureHandler) {
		filter.setAuthenticationFailureHandler(jwtAuthenticationFailureHandler);
		return this;
	}

}
